package com.example.testerclientapp;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
//import org.kxml2.kdom.Element;
//import org.kxml2.kdom.Node;
import org.w3c.dom.*;
import java.util.List;

import org.w3c.dom.Document;
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

//import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
//import org.w3c.dom.NodeList;
//import org.kxml2.kdom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.util.Log;
//import android.sax.Element;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
//import org.w3c.dom.Element;
import android.widget.TextView;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;



public class ShowAvailableSpot extends Activity {
TextView result;
ArrayList<String> result1 = new ArrayList<String>();
private static final String SOAP_ACTION = "http://spartansparking.org/reserveSpot"; 
private static final String METHOD_NAME =  "reserveSpot";       
private static final String NAMESPACE =    "http://spartansparking.org/";    
private static final String URL = "http://spartanparking.azurewebsites.net/parkingservice.asmx";   
private AndroidHttpTransport mAht;
public  SoapSerializationEnvelope mSoapEnvelope;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_show_available_spot);
		////////// SOU ///////////////
		try
        {
			
            TextView garagename = (TextView) findViewById (R.id.textView5);
              
            Button reserved = (Button) findViewById(R.id.button1);
            
			Intent getIntentVal = getIntent();
			String response = getIntentVal.getStringExtra("AvailableSpots");
			Button getlist = (Button)findViewById(R.id.button2);
			
			
			//////////////////////////// DISPLAY ALL AVAILABLE SPOTS BY PARSING response/////////////
			//Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
			TextView tv1=(TextView)findViewById(R.id.textView3);
			//tv1.setText(response);
			///////////////////////// set name of garage in textView5 //////////////
			//garagename.setText("Garage");
			
			String delim = "<spot id=";
			String temp;
			ArrayList<String> spotIdFound = new ArrayList<String>();
			ArrayList<String> floorFound = new ArrayList<String>();
			int startIdx = -1;
			int endIdx = -1;
			
			int chk = response.indexOf(delim,0);
			
			while(chk != -1)
			{
				startIdx = chk + delim.length()+1;
				endIdx = response.indexOf('\"', startIdx);
				
				temp = response.substring(startIdx, endIdx);
				spotIdFound.add(temp);
				//check the floor number
				floorFound.add(new String("Floor " + temp.charAt(1)));
				
				chk = response.indexOf(delim, endIdx);
				
			}
			
			String result = "";
			for (int i=0; i < spotIdFound.size(); i++)
			{
				result += floorFound.get(i);
				result += ": ";
				result += spotIdFound.get(i);
				result += "\n";
			}
			
			tv1.setText(result);
			///////////////////////////////
			
			int garageID = Integer.valueOf(spotIdFound.get(0))/1000;
			
			if (garageID == 1)
				garagename.setText("South Garage");
			else if (garageID ==2)
				garagename.setText("West Garage");
			else
			    garagename.setText("North Garage");
			
			
			/****String xmlString = new String(response); 
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
			DocumentBuilder builder;  
			builder = factory.newDocumentBuilder();  
             ********/
		    // Use String reader  
		    //Document document = (Document) builder.parse(new InputSource(new StringReader(xmlString)));  
		     //document.getElementsByTagName(null);
			
			
			
			//Pattern regex= <spot id="[^"]*'";
			
			//String name = response.getAttribute("name");
			
			//Matcher matcher = Pattern.compile(null).matcher(response);
			//matcher.find();
			//System.out.println(matcher.group());
			
			

	        /*****************
            textView.setText(response.toString());
            String str = removeNamespace(response.toString());
            Document document = Document.parseText(str);
            Element ele= document.getRootElement();
            List<Element> childlist = ele.elements();
            List<String> textList = new ArrayList<String>();
            for(Element child : childlist){
            textList.add(child.getTextTrim());
            
            
            *******************/
			String usrname=getIntentVal.getStringExtra("username");
			//Intent reservationSpotActivity = new Intent(ShowAvailableSpot.this, GetReservationList.class);
			
			String email = usrname;
		     ////////////////////// ON CLICKING RESERVE SPOT /////////////////
		     reserved.setOnClickListener(new View.OnClickListener()
		        {
		        	@Override
		        	public void onClick(View v)
		        	{
		        
		        //spotid = (EditText)findViewById(R.id.editText1);
		        //int spotId;
		        EditText spotid = (EditText)findViewById(R.id.editText1);
		        Intent getIntentVal = getIntent();
				
				String starttime = getIntentVal.getStringExtra("starttime");
				String endtime = getIntentVal.getStringExtra("endtime");
				String email=getIntentVal.getStringExtra("username");
				Intent reservationSpotActivity = new Intent(ShowAvailableSpot.this, GetReservationList.class);
	   			 reservationSpotActivity.putExtra("email", email);
				//Toast.makeText(getApplicationContext(), "Reserve spot My eamil is "+email, Toast.LENGTH_LONG).show();
				
				
		        String spot = spotid.getText().toString();
		        int spotId = Integer.valueOf(spot);
		        //Toast.makeText(getApplicationContext(), spot, Toast.LENGTH_LONG).show();
		     ////////////////////////////////////////////////////////
		     /////////////////CONSTRUCT ENVELOPE AND POST SOU
		     
		    	 try
			        {
				        //if ((spot.length() != 0))

				        {
				        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
				        //request.addProperty("email", email.getText().toString());
				        request.addProperty("email", email);
				        request.addProperty("starttime",starttime);
				        request.addProperty("endtime",endtime);
				        request.addProperty("spotId",spotId);
				        
				        //Toast.makeText(getApplicationContext(), email, Toast.LENGTH_LONG).show();
				        //Toast.makeText(getApplicationContext(), starttime, Toast.LENGTH_LONG).show();
				        //Toast.makeText(getApplicationContext(), endtime, Toast.LENGTH_LONG).show();
				        //Toast.makeText(getApplicationContext(), spotId, Toast.LENGTH_LONG).show();
				        
				        
				        mSoapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				        mSoapEnvelope.dotNet = true;
				        mSoapEnvelope.setOutputSoapObject(request);
				        
				        mAht = new AndroidHttpTransport(URL);
			        	mAht.call(SOAP_ACTION, mSoapEnvelope);   //in-out parameter: soapEnvelope, which means the response back will be stored in this var soapEnvelope
//			        	SoapPrimitive resultsRequestSOAP1 = (SoapPrimitive)mSoapEnvelope.getResponse();
			        	//Toast.makeText(getApplicationContext(), resultsRequestSOAP1.toString(), Toast.LENGTH_LONG).show();
			        	
			        	 if (mSoapEnvelope.bodyIn instanceof SoapFault)
			        	 {
			        		 String str= ((SoapFault) mSoapEnvelope.bodyIn).faultstring;
			        		 
			        	}
			        	else 
			        		 {
			              		 SoapPrimitive resultsRequestSOAP = (SoapPrimitive)mSoapEnvelope.getResponse();
				     
				        		 //if (resultsRequestSOAP.toString().contains("available"))
				        		 {
			      //Toast.makeText(getApplicationContext(), resultsRequestSOAP.toString(), Toast.LENGTH_LONG).show();
				        			 createAndShowDialog(resultsRequestSOAP.toString(), "Success! Your spotID= "+spotId+"and Reservation ID=");
				        			 
				        		 }
				        		 //else
				        		 	{
				        			 	// return "false" means no user found in database
				        			 	//createAndShowDialog(resultsRequestSOAP.toString(), "Server Response");
				        		 	}
			        		 }
			       
			        }
				        //else
				        	//Toast.makeText(getApplicationContext(), "Please enter SpotId", Toast.LENGTH_LONG);
			        }
			       
			        catch (Exception ex)
			        {
			        	ex.printStackTrace();
			           	Toast.makeText(getBaseContext(), "Error: "+ex.getMessage(), Toast.LENGTH_LONG).show();
			        }
		      	 
		        	}
		        	
		        	});
        ///////////////////// end on click reserve spot ////////////////////////////////
		     
		     ///////////////// on clicking get reservation list ///////////////////////
		     
		     getlist.setOnClickListener(new View.OnClickListener()
		        {
		        	@Override
		        	public void onClick(View v)
		        	{
		        		Intent getIntentVal = getIntent();
		 				String email = getIntentVal.getStringExtra("Emai");
		 				//Toast.makeText(getApplicationContext(), "ShowAvailableSpotGetList"+email, Toast.LENGTH_LONG).show();
		                 Intent ihj=new Intent(ShowAvailableSpot.this,GetReservationList.class);
		                 ihj.putExtra("email", email);
		                 startActivity(ihj);
		        
		        	}
		        	
		        	});
		 	     
		     
	}
		
            catch(Exception e)
            {
               e.printStackTrace();
            }
			
		
		
	} //end oncreate

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.show_available_spot, menu);
		return true;
	}



public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = (Document) db.parse(is); 

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }
            // return DOM
        return doc;
}



public void createAndShowDialog(String message, String title) {
	AlertDialog.Builder builder = new AlertDialog.Builder(this);

	builder.setMessage(message);
	builder.setTitle(title);
	builder.create().show();
}



}